//
//  HEAddressViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/12.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEAddressViewController.h"
#import "HESettingAddressCell.h"
#import "HEReceiveAddressModel.h"
#import "HEEditAddressViewController.h"

@interface HEAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray <HEReceiveAddressModel *> * dataSourceArr;

@end

@implementation HEAddressViewController

- (NSMutableArray<HEReceiveAddressModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的地址";
    [self setupNav];
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    
    [self loadData];
}

- (void)setupNav {
    // 设置导航栏按钮
    [self zx_setRightBtnWithText:@"添加" clickedBlock:^(UIButton * _Nonnull btn) {
        HEEditAddressViewController *vc = [HEEditAddressViewController new];
        vc.type = HEEditAddressTypeAdd;
        [vc vcBackBlock:^{
            [self.tableView.mj_header beginRefreshing];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.zx_navRightBtn.zx_tintColor = CNavLightBlackColor;
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
        _tableView.separatorColor = KHexColor(@"EEEEEE");
        _tableView.scrollsToTop = YES;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.isFromHeadRefresh = YES;
            [weakSelf loadData];
        }];
        
        [_tableView registerClass:[HESettingAddressCell class] forCellReuseIdentifier:@"HESettingAddressCell"];
    }
    return _tableView;
}

#pragma mark -

- (void)loadData {

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KaddressList parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }

        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [self.dataSourceArr addObjectsFromArray:[HEReceiveAddressModel mj_objectArrayWithKeyValuesArray:response.data]];

        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HESettingAddressCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"HESettingAddressCell"];
    cell.model = _dataSourceArr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: @"HESettingAddressCell" cacheByIndexPath:indexPath configuration:^(HESettingAddressCell *cell) {
        cell.model = self.dataSourceArr[indexPath.row];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_type == HEAddressIntoTypeToSelect) {
        if (self.selectAddressBlock) {
            self.selectAddressBlock(self.dataSourceArr[indexPath.row]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else {
        HEEditAddressViewController *vc = [HEEditAddressViewController new];
        vc.model = self.dataSourceArr[indexPath.row];
        vc.type = HEEditAddressTypeUpdate;
        [vc vcBackBlock:^{
            [self.tableView.mj_header beginRefreshing];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark -
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 收回侧滑
        [tableView setEditing:NO animated:YES];
        
        HEEditAddressViewController *vc = [HEEditAddressViewController new];
        vc.model = self.dataSourceArr[indexPath.row];
        vc.type = HEEditAddressTypeUpdate;
        [vc vcBackBlock:^{
            [self.tableView.mj_header beginRefreshing];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    editAction.backgroundColor = CNavBgColor;

    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self deleteAddressById:self.dataSourceArr[indexPath.row].id indexPath:indexPath];
    }];

    return @[deleteAction, editAction];
}

- (void)deleteAddressById:(NSInteger)addrId indexPath:(NSIndexPath *)indexPath {
 
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KaddressDelete parameters:@{@"id":[NSNumber numberWithInteger:addrId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.success) {
            
            [self.tableView.mj_header beginRefreshing];

//            // 删除cell: 必须要先删除数据源，才能删除cell
//            [self.dataSourceArr removeObjectAtIndex:indexPath.row];
//            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)selectAddress:(SelectAddress)block {
    self.selectAddressBlock = block;
}

@end
